<?php
namespace app\helpers;
use think\helper\Arr;
use think\helper\Str;
use think\Request;

class UtilHelper
{
    public static function getClientIP(Request $request=null)
    {
        $request = $request ? : \request();
        $region = explode(",", $request->header('x-forwarded-for'));
        return Arr::first($region) ?: "127.0.0.1";
    }

    /**
     * 判断当前请求是否来自移动端
     * @param string|null $userAgent 可自定义 User-Agent（默认自动获取）
     * @return bool
     */
    public static function isMobile(?string $userAgent = null): bool {
        // 若未传入 User-Agent，则自动从请求头中获取
        $userAgent = $userAgent ?? ($_SERVER['HTTP_USER_AGENT'] ?? '');

        // 空 User-Agent 默认判定为非移动端
        if (empty($userAgent)) {
            return false;
        }

        // 移动端关键词正则表达式（覆盖常见设备）
        $mobileKeywords = '/(android|webos|iphone|ipad|ipod|blackberry|windows phone|mobile|opera mini|iemobile|symbian)/i';

        // 匹配关键词则认为是移动端
        return (bool)preg_match($mobileKeywords, $userAgent);
    }

    public static  function getCardType($cardNumber) {
        // 清理卡号，只保留数字
        $cleaned = preg_replace('/\D/', '', $cardNumber);
        $length = strlen($cleaned);
        // 提取关键位数字
        $firstDigit = substr($cleaned, 0, 1);
        $firstTwoDigits = (int) substr($cleaned, 0, 2);
        $firstFourDigits = (int) substr($cleaned, 0, 4);
        $firstSixDigits = (int) substr($cleaned, 0, 6);
        $firstThreeDigits = (int) substr($cleaned, 0, 3);

        // 判断 American Express (A卡)
        if (in_array($firstTwoDigits, [34, 37]) && $length === 15) {
            return 'A';
        }

        // 判断 Discover (D卡)
        $isDiscover = false;
        if ($firstFourDigits === 6011 && in_array($length, [16, 19])) {
            $isDiscover = true;
        } elseif ($firstSixDigits >= 622126 && $firstSixDigits <= 622925 && in_array($length, [16, 19])) {
            $isDiscover = true;
        } elseif (($firstThreeDigits >= 644 && $firstThreeDigits <= 649) && in_array($length, [16, 19])) {
            $isDiscover = true;
        } elseif (($firstTwoDigits === 65) && in_array($length, [16, 19])) {
            $isDiscover = true;
        }
        if ($isDiscover) {
            return 'D';
        }

        // 判断 MasterCard (M卡)
        if (
            (($firstTwoDigits >= 51 && $firstTwoDigits <= 55) ||
                ($firstFourDigits >= 2221 && $firstFourDigits <= 2720)) &&
            $length === 16
        ) {
            return 'M';
        }

        // 判断 Visa (V卡)
        if ($firstDigit === '4' && in_array($length, [13, 16, 19])) {
            return 'V';
        }

        return 'UNKNOW';
    }

    public static function buildQueryString(array $params): string
    {
        $queryParts = [];
        foreach ($params as $key => $value) {
            if(!$key) continue;
            $queryParts[] = $key . '=' . $value;
        }
        return implode('&', $queryParts);
    }

    public static function absPath($url)
    {
        // 如果URL没有协议，自动添加http://以便parse_url正确解析
        if (!preg_match('/^https?:\/\//i', $url)) {
            $url = 'http://' . $url;
        }

        $parsed = parse_url($url);

        if (isset($parsed['host'])) {
            // 去除www前缀
            $domain = preg_replace('/^www\./i', '', $parsed['host']);
            return $domain;
        }

        return $url;
    }

}